<template>
  <div class="w1 h1">
    <div id="container"></div>
    <div class="cardBox">
          <div class="leftThreeSelect3" v-show="tc1"> 
            <el-select v-model="leftThreeValue" placeholder="请选择" :popper-append-to-body="false" @change="handleSelChange">
              <el-option v-for="item in leftThreeOptions" :key="item.name" :label="item.name" :value="item.windFarmId">
              </el-option>
            </el-select>
          </div>
      <div class="fcc fv selLayerBg borBox" style="cursor: pointer;" :class="isSel == 1 ? 'selLayerBg_s' : ''" @click="tc(1)">
        <div class="fcc">
          <el-image style="width: 14px; height: 20px"
                    :src="require(`@/assets/images/icon/selLayer${isSel == 1 ? '_1' : ''}.png`)" fit="fill"></el-image>
        </div>
        <div class="fcc f12 ctext mt10">电场图层</div>
      </div>
      <div class="fcc fv selLayerBg borBox mt10" :class="isSel == 1 ? 'selLayerBg_s' : ''">
        <div class="fcc">
          <el-image style="width: 20px; height: 20px"
                    :src="require(`@/assets/images/icon/selLayerJ${isSel == 1 ? '_1' : ''}.png`)" fit="fill"></el-image>
        </div>
        <div class="fcc f12 ctext mt10">风机图层</div>
      </div>
    </div>
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
import axios from 'axios'
import turbine from "@/views/system/turbine/index.vue";
import request from "@/utils/request";
import {getRouters} from "@/api/menu";
import router, {constantRoutes, dynamicRoutes} from "@/router";
import {filterDynamicRoutes} from "@/store/modules/permission";

export default {
  name: "map-view",
  data() {
    return {
      tc1:false,
      leftThreeValue: "全部",
      leftThreeOptions: [{
        name:"龙双",
        windFarmId:1
      }],
      AMap: null,
      map: null,
      isSel: 1,
      infoWindow: null,
      // 风机点位集合 存放 map的点位
      maskerIns1: [],
      // 风场的点位集合 存放map的点位
      maskerIns2: [],
      // 风场集合
      farmList: [],
      turbineList: []
    };
  },
  mounted() {
    let that = this;
    new Promise(resolve => {
      this.farmData();
      this.turbineData();
      resolve();
    }).then(function(){
      that.initAMap();
    })
  },
  beforeDestroy() {
    this.map?.destroy();
  },
  methods: {
    tc(){
      this.tc1 = !this.tc1;
      this.leftThreeValue='全部'
    },
    handleSelChange(){
       // 1. 销毁当前地图
    if (this.map) {
      this.map.destroy();
      this.map = null;
    }
    
    // 2. 清空现有标记点数组
    this.maskerIns1 = [];
    this.maskerIns2 = [];
    
    // 3. 根据选择的值筛选数据（如果需要）
    // const filteredFarms = this.leftThreeValue === '全部' 
    //   ? this.farmList 
    //   : this.farmList.filter(farm => farm.windFarmId === val);
    
    // 4. 重新初始化地图
    this.initAMap();
    
    this.tc1 = false;
      this.leftThreeValue='全部'
    },
    // 显示信息窗口
    showInfoWindow(marker, content) {
      if (this.infoWindow) {

        this.infoWindow.setContent(content.replaceAll("#name", marker.name));
        this.infoWindow.open(this.map, marker.getPosition());
      }
    },
    // 隐藏信息窗口
    hideInfoWindow() {
      if (this.infoWindow) {
        this.infoWindow.close();
      }
    },
    layerFun(i) {
      this.isSel = i;
      let that = this;
      // 创建信息窗口内容
      var bgImg = require("@/assets/images/windPower/windField1.png");
      var html = `<div style="background:url('${bgImg}');background-size:100% 100%;width:151px;height:58px;text-align: center;padding:0;color: #fff; line-height: 52px;">#name</div>`;
      // 初始化信息窗口
      this.infoWindow = new this.AMap.InfoWindow({
        content: html,
        isCustom: true,
        offset: new this.AMap.Pixel(0, -30)
      });
      // 选择电场
      if (i == 1) {
        this.map.remove(this.maskerIns1);
        this.map.remove(this.maskerIns2);
        // 创建一个 Icon
        var starMarktIcon = new this.AMap.Icon({
          size: new this.AMap.Size(100, 100),
          image: require("@/assets/images/icon/mark.png"),
          imageSize: new this.AMap.Size(50, 50),
        });
        that.maskerIns2=[];
        // 循环 风场
        that.farmList.forEach(x => {
          var maskerIn = new that.AMap.Marker({
            position: [131.070679, 46.844494],
            icon: starMarktIcon,
            map: that.map
          });
          maskerIn.myId = x.windFarmId;
          maskerIn.name = x.name;
          maskerIn.myType = 'farm';
          that.maskerIns2.push(maskerIn)
        })
        // 循环 风场
        that.maskerIns2.forEach(x => {
          that.addMarkerEvents(x,html);
        })
      }
      // 风机
      if (i == 2) {
        this.map.remove(this.maskerIns2);
        this.map.remove(this.maskerIns1);
        this.hideInfoWindow();
        // 创建一个 Icon
        var startIcon = new this.AMap.Icon({
          size: new this.AMap.Size(100, 100),
          image: require("@/assets/images/icon/fan.png"),
          imageSize: new this.AMap.Size(50, 50),
        });
        var startIconA = new this.AMap.Icon({
          size: new this.AMap.Size(100, 100),
          image: require("@/assets/images/icon/fan-sel.png"),
          imageSize: new this.AMap.Size(50, 50),
        });

        that.maskerIns1=[];
        // 循环 风场
        that.turbineList.forEach(x => {
          if(x.currentStatus=='01'){
            var maskerIn = new that.AMap.Marker({
              position: [x.longitude, x.latitude],
              icon: startIcon,
              map: that.map
            });
          }else{
            var maskerIn = new that.AMap.Marker({
              position: [x.longitude, x.latitude],
              icon: startIconA,
              map: that.map
            });
          }
          maskerIn.myId = x.id;
          maskerIn.name = x.turbineCode;
          maskerIn.myType = 'trubine';
          that.maskerIns1.push(maskerIn)
        })
        // 循环 风场
        that.maskerIns1.forEach(x => {
          that.addMarkerEvents(x,html);
        })
      }
    },
    // 初始化地图
    initAMap() {
      let that = this;
      window._AMapSecurityConfig = {
        securityJsCode: "d0957c89c34184763dea6f6990a9c7c8",
      };
      // 地图加载
      AMapLoader.load({
        // 申请好的Web端开发者Key，首次调用 load 时必填
        key: "ac554db0e2528f9a6170a26887a4c1fb",
        // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        version: "2.0",
        plugins: ["AMap.Scale", "AMap.DistrictSearch", "AMap.Marker", "AMap.Icon", "AMap.Pixel", "AMap.Size", "AMap.Polyline", "AMap.LngLat", "AMap.InfoWindow"],
      })
        .then((AMap) => {
          that.AMap = AMap;
          var opts = {extensions: "all"};
          var district = new AMap.DistrictSearch(opts);
          // 地图搜索双鸭山
          district.search("双鸭山", function (status, result) {
            
            var bounds = result.districtList[0].boundaries;
            var mask = [];
            for (var i = 0; i < bounds.length; i += 1) {
              mask.push([bounds[i]]);
            }

            var map = new AMap.Map("container", {
              center: [131.070679, 46.644494],
              viewMode: "3D",
              showLabel: false,
              resizeEnable: true,
              labelzIndex: 130,
              zoom: 9.8,
              layers: [
                new AMap.TileLayer.RoadNet({zIndex: 7}),
                new AMap.TileLayer.Satellite()
              ],
            });

            // 创建图标
            // 风机运行图标
            var startIcon = new AMap.Icon({
              size: new AMap.Size(50, 50),
              image: require("@/assets/images/icon/fan.png"),
              imageSize: new AMap.Size(50, 50),
            });
            var starRedtIcon = new AMap.Icon({
              size: new AMap.Size(50, 50),
              image: require("@/assets/images/icon/fan-sel.png"),
              imageSize: new AMap.Size(50, 50),
            });
            //风场图标
            var starMarktIcon = new AMap.Icon({
              size: new AMap.Size(50, 50),
              image: require("@/assets/images/icon/mark.png"),
              imageSize: new AMap.Size(50, 50),
            });
            // 循环 风场
           // 在 initAMap 方法中修改风场图标的创建部分
            that.farmList.forEach(x => {
              var maskerIn = new AMap.Marker({
                position: [131.070679, 46.844494],
                icon: starMarktIcon,
                map: map
              });
              maskerIn.myId = x.windFarmId;
              maskerIn.name = x.name;
              maskerIn.myType = 'farm';
              that.maskerIns2.push(maskerIn);

              // 添加跳动动画
              let offsetY = 0;
              let direction = -1; // 初始方向向上
              const animate = () => {
                offsetY += direction * 0.3; // 调整速度和幅度
                if (offsetY <= -10) direction = 1;  // 到达顶点后下落
                if (offsetY >= 0) direction = -1;   // 落到底部后上升
                maskerIn.setOffset(new AMap.Pixel(0, offsetY));
                requestAnimationFrame(animate);
              };
              animate();
            });
            //循环 风机
            that.turbineList.forEach(x => {
              var maskerIn = new AMap.Marker({
                position: [x.longitude, x.latitude],
                icon: startIcon,
                map: map
              });
              maskerIn.myId = x.id;
              maskerIn.name = x.turbineCode;
              maskerIn.myType = 'trubine';
              that.maskerIns1.push(maskerIn)
            })

            // 创建信息窗口
            var bgImg = require("@/assets/images/windPower/windField1.png");
            var html = `<div style="background:url('${bgImg}');background-size:100% 100%;width:151px;height:58px;text-align: center;padding:0;color: #fff; line-height: 52px;">#name</div>`;

            that.infoWindow = new AMap.InfoWindow({
              content: html,
              isCustom: true,
              offset: new AMap.Pixel(30, 0)
            });
            // 循环 风场
            that.maskerIns2.forEach(x => {
              that.addMarkerEvents(x,html);
            })
            //循环 风机
            that.maskerIns1.forEach(x => {
              that.addMarkerEvents(x,html);
            })

            // 添加区域描边
            for (var i = 0; i < bounds.length; i += 1) {
              new AMap.Polyline({
                path: bounds[i],
                strokeColor: "#99ffff",
                strokeWeight: 4,
                map: map,
              });
            }
            that.map = map;
          });
        })
        .catch((e) => {
          console.log(e);
        });
    },
    // 风场
    async farmData() {
      const _that = this;
      request({
        url: '/system/farm/getlistFarm',
        method: 'get',
      }).then(response => {
        _that.farmList = response.rows;
      });
    },
    // 风机
    async turbineData() {
      const _that = this;
      request({
        url: '/fjfd/turbine/listTurbine',
        method: 'get',
      }).then(response => {
        _that.turbineList = response.rows;
      });
    },
    // 添加标记事件
    addMarkerEvents(marker,html) {
      let that = this;
      marker.on('mouseover', function (e) {
        that.showInfoWindow(marker, html);
      });
      marker.on('mouseout', function (e) {
        that.hideInfoWindow();
      });
      marker.on('click', function (e) {
        if (marker.myType === 'farm') {
          const obj = that.farmList.find(x => x.windFarmId == marker.myId);
          that.$router.push({path: "/dianchangDetail?windFarmId="+obj.windFarmId});
        } else {
          const obj = that.turbineList.find(x => x.id == marker.myId);
          that.$router.push({
            path: "/fengJiDetail",
            query: {
              windTurbineId: obj.id,       // 第一个参数
              windTurbinename: obj.turbineCode    // 第二个参数
            }
          });
        }
      });
    }
  },
};
</script>
<style scoped>
#container {
  width: 100%;
  height: 100%;
}

.cardBox {
  position: absolute;
  top: 40%;
  right: 480px;
  z-index: 170;
}

.selLayerBg {
  background-image: url("~@/assets/images/icon/selLayerBg.png");
}

.selLayerBg_s {
  background-image: url("~@/assets/images/icon/selLayerBg_.png");
}

.borBox {
  width: 60px;
  height: 60px;
  background-size: 100% 100%;
  /* cursor: pointer; */
}

.ctext {
  color: #0aa7ff;
}

.selLayerBg_s .ctext {
  color: #36f5f7;
}

::v-deep .amap-info-content {
  padding: 0px;
  background: none;
  color: #ffffff;
  font-size: 14px;
  line-height: 58px;
}

::v-deep .amap-info-sharp {
  display: none;
}

::v-deep .amap-info-close {
  top: 0;
  right: 0;
}

.leftThreeSelect3 {
  position: absolute;
  top: 10px;
  right: 70px;
  width: 70px;
  .el-input__inner{
    background: #4797f266!important;
    height: 40px!important;
    line-height: 38px!important;
    color:#fff!important;
  }
}
</style>
